package net.esj.basic.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.esj.basic.utils.Validators;
import net.esj.basic.utils.SessionKeyConstants;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public abstract class NormalLoginAbstractInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation inv) throws Exception {
		Object o = inv.getInvocationContext().getSession().get(SessionKeyConstants.NORMAL_USER);
		ActionContext actionContext = inv.getInvocationContext();   
		if (o == null || o.getClass() !=  getSessionClass()) {
			HttpServletRequest request= (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);   
			HttpServletResponse response= (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);
			if(checkMethodHasReturnValue(inv)){//没有返回code表示为AJAX操作
				return getReturnLogin(request,response,inv);
			}else{
				return writeString(request, response,inv);
			}
        }
        return inv.invoke();
	}

	public abstract Class getSessionClass();
	
	public abstract String getReturnLogin(HttpServletRequest request,HttpServletResponse response,ActionInvocation inv);
	
	public abstract String writeString(HttpServletRequest request,HttpServletResponse response,ActionInvocation inv);
	
	public boolean checkMethodHasReturnValue(ActionInvocation inv){
		Object o = inv.getAction();
		String methodName = inv.getProxy().getMethod();
		try {
			Method method = o.getClass().getMethod(methodName);
			if(void.class ==method.getReturnType()){
				return false;
			}else{
				return true;
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return true;
	}
}
